//
//  HNightQualiatyViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/6/19.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HNightQualiatyViewController.h"
#import "HNightQualityTableViewCell.h"
#import "TableQcStandard.h"
#import "HQcTypeModel.h"
#import "MPickerSelectionView.h"
#import "HQCDepartViewController.h"
#import "Model_Pub_Employee.h"
#import "Model_Hr_InspectDetail_New.h"
#import "Model_Hr_Ns_Inspect_New.h"
#import "HQualitySave.h"
#import <TMCache.h>
#import "TablePubDictionaryItem.h"
@interface HNightQualiatyViewController ()
<UITableViewDelegate,
UITableViewDataSource,
MPickerSelectionViewProtocol,
UITextViewDelegate,
UITextFieldDelegate>
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic ,strong) NSMutableArray *starnardArray;
@property (nonatomic ,strong) NSDictionary *menuParam;
@property (nonatomic ,strong) HQc_codeModel *model;
@property (nonatomic ,strong) UITableView *tableview;
@property (nonatomic ,strong) UILabel *TitleLabel;
@property (nonatomic ,strong) UIButton *HnightButton;
@property (nonatomic ,strong) UIView *headview;
@property (nonatomic ,strong) UIDatePicker *datePicker;
@property (nonatomic ,strong) MPickerSelectionView *pickerSelectionView;
@property (nonatomic ,strong) UIButton *dateTimeButton;
@property (nonatomic ,strong) UIButton *NursingUnitButton;
@property (nonatomic ,strong) UIButton *TimeIntervalButton;
@property (nonatomic ,strong) UIButton *nurserButton;
@property (nonatomic ,strong) UIButton *otherNurserButton;
@property (nonatomic ,strong) UILabel *checkerLabel;
@property (nonatomic ,strong) UITextField *RemarksTextview;
@property (nonatomic ,strong) NSMutableArray *arrays;
@property (nonatomic ,strong) NSMutableArray *dept_nameArray;
@property (nonatomic ,copy) NSString *dateString;
@property (nonatomic ,strong) Model_Hr_Ns_Inspect_New *inspectModel;
@property (nonatomic ,strong) NSMutableArray *bigArray;
@property (nonatomic ,strong) NSMutableDictionary *bigDic;
@property (nonatomic ,strong) NSMutableArray *timeInterArray;

@end

@implementation HNightQualiatyViewController

- (instancetype)initWithMenuParam:(NSDictionary *)meneParam
{
    if (self) {
        self.menuParam = meneParam;
        self.arrays = [NSMutableArray new];
        self.dept_nameArray = [NSMutableArray new];
        self.bigArray = [NSMutableArray new];
        self.timeInterArray = [NSMutableArray new];
        self.dataArray = [[[TableQcStandard alloc]init]GetHnightQuality:[self.menuParam objectForKey:@"STANDARD_ID"]];

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.bigDic = [NSMutableDictionary new];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableview];
    [self assigmentData];
    UIBarButtonItem *execbtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(didSaveButttonClicked:)];
    self.navigationItem.rightBarButtonItem = execbtn;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentTextViewDidediting:) name:UITextFieldTextDidChangeNotification object:nil];
    
    [self KeyBord];
    
}
- (UITableView *)tableview
{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth , ScreenHeight-NavBarHeight) style:UITableViewStyleGrouped];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        _tableview.tableFooterView = [[UIView alloc]init];
        [_tableview registerClass:[HNightQualityTableViewCell class] forCellReuseIdentifier:@"cell"];
    }
    return _tableview;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HNightQualityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HQc_codeModel *model = self.dataArray[indexPath.row];
    cell.textview.tag = indexPath.row;
    cell.savedata = ^(NSString *string) {
    
        [self.bigDic setObject:string forKey:@(indexPath.row)];
    };
    NSArray *arr = [self.bigDic allKeys];
    if ([arr containsObject:@(indexPath.row)]) {
        cell.textview.text = [self.bigDic objectForKey:@(indexPath.row)];
    }else {
        cell.textview.text = @"";
    }
    cell.titleLabel.text = [NSString stringWithFormat:@"%ld. %@",indexPath.row + 1, model.CODE_NAME];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.headview = [[UIView alloc]init];
    self.headview.backgroundColor = [UIColor whiteColor];
    
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, ScreenWidth, 30)];
    titleLabel.text = @"问题记录 (注:没有问题,可以不用填写)";
    [self setUpHnightLabel];
    [self.headview addSubview:titleLabel];
    [self.headview addSubview:self.dateTimeButton];
    
    _NursingUnitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _NursingUnitButton.frame = CGRectMake(self.TitleLabel.right + 10, 80,ScreenWidth - self.TitleLabel.right - 15, 30);
    _NursingUnitButton.backgroundColor = [UIColor whiteColor];
    _NursingUnitButton.layer.borderColor = [RGB(212,212,212) CGColor];
    _NursingUnitButton.layer.borderWidth = 0.3f;
    _NursingUnitButton.layer.masksToBounds = YES;
    _NursingUnitButton.layer.cornerRadius = 5;
    [_NursingUnitButton setTitle:self.inspectModel.dept_name?:@"" forState:UIControlStateNormal];
    _NursingUnitButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_NursingUnitButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _NursingUnitButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_NursingUnitButton addTarget:self action:@selector(nusingDepart:) forControlEvents:UIControlEventTouchUpInside];
    [self.headview addSubview:_NursingUnitButton];
    
    
    _TimeIntervalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _TimeIntervalButton.frame = CGRectMake(self.TitleLabel.right + 10, 120 , ScreenWidth - self.TitleLabel.right - 15, 30);
    _TimeIntervalButton.backgroundColor = [UIColor whiteColor];
    _TimeIntervalButton.layer.borderColor = [RGB(212,212,212) CGColor];
    _TimeIntervalButton.layer.borderWidth = 0.3f;
    _TimeIntervalButton.layer.masksToBounds = YES;
    _TimeIntervalButton.layer.cornerRadius = 5;
    _TimeIntervalButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_TimeIntervalButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_TimeIntervalButton setTitle:self.inspectModel.round_name?:@"" forState:UIControlStateNormal];
    _TimeIntervalButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_TimeIntervalButton addTarget:self action:@selector(TimeInter:) forControlEvents:UIControlEventTouchUpInside];
    [self.headview addSubview:_TimeIntervalButton];
    
    
    _nurserButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nurserButton.frame = CGRectMake(self.TitleLabel.right + 10, 160 , ScreenWidth - self.TitleLabel.right - 15, 30);
    _nurserButton.backgroundColor = [UIColor whiteColor];
    _nurserButton.layer.borderColor = [RGB(212,212,212) CGColor];
    _nurserButton.layer.borderWidth = 0.3f;
    _nurserButton.layer.masksToBounds = YES;
    _nurserButton.layer.cornerRadius = 5;
    _nurserButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_nurserButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_nurserButton setTitle:self.inspectModel.NURSE_NAME?:@"" forState:UIControlStateNormal];
    _nurserButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_nurserButton addTarget:self action:@selector(nurser:) forControlEvents:UIControlEventTouchUpInside];
    [self.headview addSubview:_nurserButton];
    
    
    _otherNurserButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _otherNurserButton.frame = CGRectMake(self.TitleLabel.right + 10, 200 , ScreenWidth - self.TitleLabel.right - 15, 30);
    _otherNurserButton.backgroundColor = [UIColor whiteColor];
    _otherNurserButton.layer.borderColor = [RGB(212,212,212) CGColor];
    _otherNurserButton.layer.borderWidth = 0.3f;
    _otherNurserButton.layer.cornerRadius = 5;
    _otherNurserButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_otherNurserButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_otherNurserButton setTitle:self.inspectModel.OTHHER_CHAECK_NAME?:@"" forState:UIControlStateNormal];
    _otherNurserButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_otherNurserButton addTarget:self action:@selector(otherNurser:) forControlEvents:UIControlEventTouchUpInside];
    [self.headview addSubview:_otherNurserButton];
    
    
    _checkerLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.TitleLabel.right + 10, 240 , ScreenWidth - self.TitleLabel.right - 15, 30)];
    _checkerLabel.backgroundColor = [UIColor whiteColor];
    _checkerLabel.layer.borderWidth = 0.3f;
    _checkerLabel.layer.masksToBounds = YES;
    _checkerLabel.layer.cornerRadius = 5;
    _checkerLabel.layer.borderColor = [RGB(212,212,212) CGColor];
    _checkerLabel.text = self.inspectModel.CHECKER_NAME?:@"";
    _checkerLabel.textAlignment = NSTextAlignmentCenter;
    _checkerLabel.font = [UIFont systemFontOfSize:14];
    [self.headview addSubview:_checkerLabel];
    
    
    _RemarksTextview = [[UITextField alloc]initWithFrame:CGRectMake(120,280, ScreenWidth - 110 - 15, 35)];
    _RemarksTextview.delegate = self;
    _RemarksTextview.layer.borderWidth = 0.1;
    _RemarksTextview.layer.cornerRadius = 6.0;
    _RemarksTextview.layer.masksToBounds = YES ;
    _RemarksTextview.tag = 100;
//    _RemarksTextview.text = self.inspectModel.REMARKS?:@"";
    [self.headview addSubview:_RemarksTextview];
    
    
    
    return self.headview;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 320;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (void)contentTextViewDidediting:(NSNotification *)noti
{

    UITextField *textView = noti.object;
    
    if (textView.tag == 100) {
        
        if (textView.text.length == 0) {
            
            self.inspectModel.REMARKS = @"";
            
        }else {
            
            self.inspectModel.REMARKS = textView.text;
        }
    }else {
        HQc_codeModel *model = self.dataArray[textView.tag];
        Model_Hr_InspectDetail_New *new_model = self.bigArray[textView.tag];
        model.reason = textView.text?:@"";
        new_model.RESION = textView.text?:@"";
    }
    
    NSLog(@"====%@",self.inspectModel.REMARKS);
}



- (MPickerSelectionView *)pickerSelectionView {
    if (!_pickerSelectionView) {
        _pickerSelectionView = [[MPickerSelectionView alloc]init];
        _pickerSelectionView.delegate = self;
        
    }
    return _pickerSelectionView;
}
- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc]init];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    }
    return _datePicker;
}
- (void)dateTime:(UIButton *)sender
{
    [self.pickerSelectionView present];
    
}


- (UIView *)viewWithMPickerSelectionView:(MPickerSelectionView *)pickerSelectionView {
    return self.datePicker;
}

- (void)confirmEventWithMPickerSelectionView:(MPickerSelectionView *)pickerSelectionView
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
    self.dateString = [dateFormat stringFromDate:self.datePicker.date];
    self.inspectModel.CHECK_DATE = self.dateString;
    [self.dateTimeButton setTitle:self.dateString forState:UIControlStateNormal];
    
}

- (void)setUpHnightLabel
{
    NSArray *titleArray = @[@"查房日期",@"护理单元",@"查房时段",@"责任值班护士",@"其他值班护士",@"检查者",@"备注"];
    for (int i = 0; i < 7; i ++) {
        self.TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 40 + 40 *i, 100, 30)];
        self.TitleLabel.text = titleArray[i];
        self.TitleLabel.font = [UIFont systemFontOfSize:14];
        [self.headview addSubview:self.TitleLabel];
    }
}

- (UIButton *)dateTimeButton
{
    if (!_dateTimeButton) {
        _dateTimeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _dateTimeButton.frame = CGRectMake(self.TitleLabel.right + 10, 40 , ScreenWidth - self.TitleLabel.right - 15, 30);
        _dateTimeButton.backgroundColor = [UIColor whiteColor];
        _dateTimeButton.layer.borderColor = [RGB(212,212,212) CGColor];
        _dateTimeButton.layer.borderWidth = 0.3f;
        _dateTimeButton.layer.masksToBounds = YES;
        _dateTimeButton.layer.cornerRadius = 5;
        _dateTimeButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_dateTimeButton setTitle:[super getNowDate] forState:UIControlStateNormal];
        self.inspectModel.CHECK_DATE = [super getNowDate];
        [_dateTimeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _dateTimeButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_dateTimeButton addTarget:self action:@selector(dateTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dateTimeButton;
}
- (void)nusingDepart:(UIButton *)sender
{
    HQCDepartViewController *HQCDVC = [[HQCDepartViewController alloc]initWithType:1 modelArray:nil standard_id:[self.menuParam objectForKey:@"STANDARD_ID"]];
    UINavigationController *navHQCDVC = [[UINavigationController alloc]initWithRootViewController:HQCDVC];
    HQCDVC.title = @"选择";
    HQCDVC.getBlocks = ^(NSString *dept_name , NSString *dept_id) {
        self.inspectModel.DEPT_ID = dept_name;
        self.inspectModel.dept_name = dept_id;
        [self.tableview reloadData];
    };
    [self presentViewController:navHQCDVC animated:YES completion:NULL];
    
}
- (void)nurser:(UIButton *)sender
{
    
    HQCDepartViewController *HQCDVC = [[HQCDepartViewController alloc]initWithType:3 modelArray:nil standard_id:nil];
    UINavigationController *navHQCDVC = [[UINavigationController alloc]initWithRootViewController:HQCDVC];
    HQCDVC.title = @"选择";
    HQCDVC.getBlock_nurse = ^(NSString *nurse_name, NSString *nurse_id)  {
        self.inspectModel.NURSE_NAME = nurse_name;
        self.inspectModel.NURSE_ID = nurse_id;
        [self.tableview reloadData];
    };
    [self presentViewController:navHQCDVC animated:YES completion:NULL];

}
- (void)otherNurser:(UIButton *)sender
{
        HQCDepartViewController *HQCDVC = [[HQCDepartViewController alloc]initWithType:2 modelArray:self.arrays standard_id:nil];
        UINavigationController *navHQCDVC = [[UINavigationController alloc]initWithRootViewController:HQCDVC];
        HQCDVC.title = @"选择";
        HQCDVC.getBlock = ^(NSArray *array) {
            self.arrays = (NSMutableArray *)array;
            NSMutableArray *id_array = [NSMutableArray new];
            for (Model_Pub_Employee *model in array) {
                if (![self.dept_nameArray containsObject:model.EMP_NAME]) {
                    [self.dept_nameArray addObject:model.EMP_NAME];
                }
                if (![id_array containsObject:model.EMP_ID]) {
                    [id_array addObject:model.EMP_ID];
                }
            }
            
            NSString *string = [self.dept_nameArray componentsJoinedByString:@","];
            NSString *idString = [id_array componentsJoinedByString:@","];
            self.model.OthercheckPeople = string;
            self.inspectModel.OTHHER_CHAECK_NAME = string?:@"";
            self.inspectModel.OTHHER_CHAECK_ID = idString?:@"";
            [self.tableview reloadData];
        };
        [self presentViewController:navHQCDVC animated:YES completion:NULL];

}

- (void)TimeInter:(UIButton *)sender
{
    HQCDepartViewController *HQCDVC = [[HQCDepartViewController alloc]initWithType:4 modelArray:nil standard_id:nil];
    UINavigationController *navHQCDVC = [[UINavigationController alloc]initWithRootViewController:HQCDVC];
    HQCDVC.title = @"选择";
    HQCDVC.getBlock_Item = ^(NSString *item_id , NSString *item_name) {
        self.inspectModel.ROUND_HOURS = item_id;
        self.inspectModel.round_name = item_name;
        [self.tableview reloadData];
    };
    [self presentViewController:navHQCDVC animated:YES completion:NULL];

}
#pragma mark 给主表和明细表赋值
- (void)assigmentData
{
    self.inspectModel = [[Model_Hr_Ns_Inspect_New alloc]init];
    self.inspectModel.RESULT_ID = [super createPrimaryID];

        for (int i = 0; i < self.dataArray.count; i++) {
        HQc_codeModel *model = self.dataArray[i];
        Model_Hr_InspectDetail_New *detailModel = [[Model_Hr_InspectDetail_New alloc]init];
        detailModel.RESULT_ID = self.inspectModel.RESULT_ID;
        detailModel.CODE_ID = model.CODE_ID;
        detailModel.SCORE = [model.SCORE floatValue];
        detailModel.RESION = @"";
        detailModel.UPLOAD_FLAG = 0;
        [self.bigArray addObject:detailModel];
    }
    self.inspectModel.LEVEL_ID = [self.menuParam objectForKey:@"LEVEL_ID"];
    self.inspectModel.TYPE_ID = [self.menuParam objectForKey:@"TYPE_ID"];
    self.inspectModel.CODE_ID = @"*";
    self.inspectModel.STANDARD_ID = [self.menuParam objectForKey:@"STANDARD_ID"];
    self.inspectModel.CHECKER_ID = [UserDefault getUserInfo].USER_ID;
    self.inspectModel.CHECKER_NAME = [UserDefault getUserInfo].USER_NAME;
    self.inspectModel.SCORE = @"";
    self.inspectModel.REMARKS = @"";
    self.inspectModel.INPUT_USER_ID = [UserDefault getUserInfo].USER_ID;
    self.inspectModel.INPUT_USER_NAME = [UserDefault getUserInfo].USER_NAME;
    self.inspectModel.INPUT_DATE = [super getNowDate];
}

#pragma mark 保存
- (void)didSaveButttonClicked:(UIButton *)sender
{
    if (self.inspectModel.DEPT_ID.length == 0) {
        [HCommon popupErrorMessage:@"护理单元不能为空"];
        return;
    }
    if (self.inspectModel.ROUND_HOURS.length == 0) {
        [HCommon popupErrorMessage:@"检查时段不能为空"];
        return;

    }
    if (self.inspectModel.NURSE_NAME.length == 0) {
        [HCommon popupErrorMessage:@"值班护士不能为空"];
        return;
        
    }

    NSMutableArray *reasonArray = [NSMutableArray new];
    
    for (int i = 0; i < self.bigArray.count; i ++) {
        Model_Hr_InspectDetail_New *detail_model = self.bigArray[i];
        if (detail_model.RESION.length > 0) {
            [reasonArray addObject:detail_model.RESION];
        }
    }
    self.inspectModel.SCORE = @"0";
    self.inspectModel.UPLOAD_FLAG = 0;
    self.inspectModel.RESUL = [reasonArray componentsJoinedByString:@","];
    [[HQualitySave alloc]initWithFormData:self.inspectModel inspectDetailArray:self.bigArray];
    [HCommon popupSuccessMessage:@"保存成功"];
    NSNotification * notice = [NSNotification notificationWithName:@"HNightRefresh" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 监听键盘,回收
- (void)KeyBord
{
    //点击空白处回收键盘
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
    //添加观察者 当键盘弹出时，tableview随之上移,不会遮挡
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

//这一句不能去掉  否则点击屏幕的任何一个地方都会崩溃
- (void)keyboardHide:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
}
#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableview.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.tableview.contentInset = UIEdgeInsetsZero;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
